import React, { useState, useEffect } from 'react';
import style from './index.module.scss';

const CountdownToNextMonday = () => {
    const [countdown, setCountdown] = useState({
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
    });

    useEffect(() => {
        const updateCountdown = () => {
            const now = new Date().getTime();
            const targetTime = getNextMonday();

            if (targetTime - now <= 0) {
                clearInterval(intervalId);
                return;
            }

            const timeDifference = targetTime - now;
            const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
            const hours = Math.floor(
                (timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
            );
            const minutes = Math.floor(
                (timeDifference % (1000 * 60 * 60)) / (1000 * 60)
            );
            const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

            setCountdown({ days, hours, minutes, seconds });
        };

        const intervalId = setInterval(updateCountdown, 1000);

        updateCountdown(); // 立即更新一次

        return () => clearInterval(intervalId); // 清除定时器
    }, []);

    const getNextMonday = () => {
        const now = new Date();
        const today = now.getDay();
        let daysUntilNextMonday = 8 - today;
        if (daysUntilNextMonday > 7) {
            daysUntilNextMonday -= 7;
        }
        const nextMonday = new Date(
            now.setDate(now.getDate() + daysUntilNextMonday)
        );
        nextMonday.setHours(0, 0, 0, 0);
        return nextMonday;
    };

    return (
        <div className={style.timeBox}>
            {countdown.days}天{countdown.hours}时{countdown.minutes}分
            {countdown.seconds}秒
        </div>
    );
};

export default CountdownToNextMonday;
